/*
 * @Author: AuroCaffe 18509564594@163.com
 * @Date: 2025-06-13 11:02:08
 * @LastEditors: AuroCaffe 18509564594@163.com
 * @LastEditTime: 2025-07-25 21:27:28
 * @FilePath: \HuiLin\utils\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import Request from "@/lib/request/index.js";
import {
	refreshTokenFn
} from "@/api/login.js";
import storage from "@/utils/storage.js";
import {
	md5
} from "@/utils/md5.js";
import Foundation from "@/utils/Foundation.js";
import API from "@/config/api.js";

import uuid from "@/utils/uuid.modified.js";
import jwt from '@/js_sdk/t-jwt/jwt.js'
import store from "../store";


let isNavigateTo = false

function cleanStorage() {
	uni.showToast({
		title: "你的登录状态已过期，请重新登录",
		icon: "none",
		duration: 1500,
	});
	if (uni.showLoading()) {
		uni.hideLoading();
	}

	storage.setHasLogin(false);
	storage.setAccessToken("");
	storage.setRefreshToken("");
	console.log("清空token");
	storage.setUuid("");
	storage.setUserInfo({});


	if (!isNavigateTo) {
		isNavigateTo = true
		// 防抖处理跳转
		// #ifdef MP-WEIXIN
		this.$router.smartNavigate({
			url: "/pages/passport/wechatMPLogin",
		});
		// #endif
		// #ifndef MP-WEIXIN
		this.$router.smartNavigate({
			url: "/pages/passport/login",
		});
		//  #endif
	}
}

let http = new Request();


/**
 * 创建uuid方法
 */
const createUuid = () => {
	if (!storage.getUuid()) {
		storage.setUuid(uuid.v1());
		console.log("uuid", storage.getUuid());
	}
}


http.setConfig((config) => {
	// createUuid();
	/* 设置全局配置 */
	config.baseURL = API.api
	config.header = {
		...config.header,
	};
	config.validateStatus = (statusCode) => {
		// 不论什么状态,统一在正确中处理
		return true;
	};
	return config;
});

http.interceptors.request.use(
	(config) => {
		// console.log(config);
		/* 请求之前拦截器。可以使用async await 做异步操作 */
		let accessToken = storage.getAccessToken();
		if (accessToken) {
			/**
			 * 使用JWT解析
			 * 小于当前时间将当前token清除
			 */
			try {
				const decodeJwt = jwt(accessToken);
				const timing = new Date().getTime() / 1000;
				if (decodeJwt.exp <= timing) {
					// console.log('Token已过期，清除token');
					accessToken = "";
					storage.setAccessToken('');
				}
			} catch (error) {
				// console.log('JWT解析失败，可能是无效token');
				accessToken = "";
				storage.setAccessToken('');
			}

			if (accessToken) {
				config.header['authorization'] = 'Bearer ' + accessToken;
			}


		}
		// createUuid(); // 减少不必要的UUID生成
		config.header = {
			...config.header,
			// uuid: storage.getUuid()
		};
		return config;
	},
	(config) => {
		return Promise.reject(config);
	}
);


// 是否正在刷新的标记
let isRefreshing = false;
//重试队列
let requests = [];
// 必须使用异步函数，注意
http.interceptors.response.use(
	async (response) => {
			/* 请求之后拦截器。可以使用async await 做异步操作  */
			// 移除自动隐藏loading的逻辑，让页面自己控制loading状态
			// uni.showLoading() ? uni.hideLoading() : ''

			let token = storage.getAccessToken();
			let oldRefreshToken = storage.getRefreshToken();

			// 检查是否需要刷新token
			if (
				(oldRefreshToken && response.statusCode === 401) ||
				response.data?.code === 401 ||
				response.data?.status === 401
			) {
				if (!isRefreshing) {
					console.log('Token过期，开始刷新token');
					console.log('当前refreshToken:', oldRefreshToken);

					if (!oldRefreshToken) {
						console.log('没有refreshToken，直接清空存储');
						cleanStorage();
						return Promise.reject(new Error('没有refreshToken'));
					}

					isRefreshing = true;
					storage.setAccessToken('');

					// 调用刷新token的接口
					return refreshTokenFn(oldRefreshToken)
						.then((res) => {
							console.log('刷新token响应:', res);
							if (res.data?.code === 200 && res.data?.data) {
								let {
									accessToken,
									refreshToken
								} = res.data.data;
								storage.setAccessToken(accessToken);
								storage.setRefreshToken(refreshToken);

								// token 刷新后将数组的方法重新执行
								console.log('Token刷新成功，重新执行请求队列');
								requests.forEach((cb) => cb(accessToken));
								requests = []; // 重新请求完清空
								return http.request(response.config);
							} else {
								throw new Error('刷新token响应格式错误');
							}
						})
						.catch((err) => {
							console.log('刷新token失败:', err);
							cleanStorage();
							return Promise.reject(err);
						})
						.finally(() => {
							isRefreshing = false;
						});
				} else {
					// 返回未执行 resolve 的 Promise
					return new Promise((resolve) => {
						// 用函数形式将 resolve 存入，等待刷新后再执行
						requests.push((token) => {
							resolve(http.request(response.config));
						});
					});
				}
			}

			// 如果当前返回没登录且没有refresh token
			if (
				(!token && !storage.getRefreshToken() && response.statusCode === 401) ||
				response.data?.code === 401
			) {
				console.log('没有token以及refresh token，跳转登录');
				cleanStorage();
			}

			return response;
		},
		(error) => {
			return error;
		}
);

export {
	http
};

export const Method = {
	GET: "GET",
	POST: "POST",
	PUT: "PUT",
	DELETE: "DELETE",
};